package hc.um.action;

import hc.tool.UtilityServiec;
import hc.um.Drug;
import hc.um.service.UserService;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterDrugServlet
 */
@WebServlet("/RegisterDrugServlet")
public class RegisterDrugServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserService();	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterDrugServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		try {
			this.registerDrug(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public void registerDrug(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SQLException {
		Drug drug = new Drug();
		
		int drugid = 0;
		
		if( (drugid = UtilityServiec.getDrugID()) < 0 )
		{
			response.getWriter().write(creatXmlTextRegisterDrug("Fail","Gererate drug id failed!",0));
			return;
		}
		
		drug.setID(drugid);
		drug.setName(request.getParameter("name"));
		drug.setSpecification(request.getParameter("specification"));
		
		if ( userService.addDrug(drug) == 1 )
		{
			response.getWriter().write(creatXmlTextRegisterDrug("Success","Registered drug successfully!",drugid));
		} 
		else 
		{
			response.getWriter().write(creatXmlTextRegisterDrug("Fail","Registered drug failed.",0));
		}
	}
	
	public String creatXmlTextRegisterDrug(String result, String message, int drugid) {
		String xmltext = null;

		xmltext = "<registerdrug><result>" + result + "</result><message>"
				+ message + "</message><drugid>" + drugid + "</drugid></registerdrug>";
		//System.out.println("xmltext="+xmltext);
		
		return xmltext;
	}	

}
